
import { Component } from 'react';

import './Calculator.css';

import BoilingVerdict from './BoilingVerdict';
import TemperatureInput from './TemperatureInput';

// 将华氏温度转化为摄氏温度
function toCelsius(fahrenheit) {
  let value = parseFloat( fahrenheit );
  if( Number.isNaN( value ) ){
    return '';
  }
  let result = ( value - 32 ) * 5 / 9 ;
  return result;
}

// 将摄氏温度转化为华氏温度
function toFahrenheit(celsius) {
  let value = parseFloat( celsius );
  if( Number.isNaN( value ) ){
    return '';
  }
  return ( value * 9 / 5 ) + 32;
}

class Calculator extends Component {
    constructor(props) {
        super(props);
        this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
        this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
        // 初始化组件状态
        this.state = {
            // 表示温度的属性
            temperature: '',
            // 标度(用于区分 摄氏温度 和 华氏温度)
            scale: 'C'
        };
    }
    handleCelsiusChange(value) {
      this.setState({scale: 'C', temperature: value});
    }
    handleFahrenheitChange(value) {
      this.setState({scale: 'F', temperature: value});
    }
    render() {
      // 从组件状态中获取温度数据
      const temperature = this.state.temperature;
      const scale = this.state.scale;
      const celsius = scale === 'F' ? toCelsius( temperature ) : temperature ;
      const fahrenheit = scale === 'C' ? toFahrenheit( temperature ) : temperature ;
      console.log( fahrenheit );
      return (
        <>
          <TemperatureInput scale="C" 
                            temperature={celsius} 
                            onTemperatureChange={ this.handleCelsiusChange }>
          </TemperatureInput>

          <TemperatureInput scale="F" 
                            temperature={fahrenheit} 
                            onTemperatureChange={ this.handleFahrenheitChange }>
          </TemperatureInput>

          <BoilingVerdict celsius={ temperature }/>
        </>
      );
    }
}

export default Calculator;